//
//  AddLessonShareViewController.m
//  LoveDraw
//
//  Created by 零零壹 on 2017/7/13.
//  Copyright © 2017年 梁晨. All rights reserved.
//

#import "AddLessonShareViewController.h"
#import <JCTagListView.h>
#import "PlaceholderTextView.h"
#import "JFImagePickerController.h"
#import "animationView.h"

@interface AddLessonShareViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,JFImagePickerDelegate>
{
    NSMutableArray *photos;
    UICollectionView *photosList;
}
@property(nonatomic,strong)NSMutableArray *ClassArr;
@property(nonatomic,strong)JCTagListView *TagV;
@property(nonatomic,strong)NSMutableArray *photoArr; // 要上传给后台的东西
@property(nonatomic,strong)UIScrollView *scrV;
@property(nonatomic,strong)PlaceholderTextView *textV;
@property(nonatomic,strong)UIButton *FaBuBtn;

@end

@implementation AddLessonShareViewController

-(NSMutableArray *)ClassArr
{
    if (!_ClassArr) {
        _ClassArr = [NSMutableArray array];
    }
    return _ClassArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"发布课例";
    [self CreateSrcV];
    [self CreateTagV];
    [self CreateTextV];
    [self CreateFabu];
    [self GetClassRequest];
    //代码开始
    self.extendedLayoutIncludesOpaqueBars = YES;
//    self.automaticallyAdjustsScrollViewInsets = NO;
    self.edgesForExtendedLayout = UIRectEdgeAll;
    
    photos = [[NSMutableArray alloc] init];
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 5;
    NSInteger size = (MAIN_SCREEN_WIDTH-40)/5;
    if (size%2!=0) {
        size-=1;
    }
    flowLayout.itemSize = CGSizeMake(size, size);
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);

    photosList = [[UICollectionView alloc] initWithFrame:CGRectMake(15, 50+self.TagV.frame.size.height+10+20+10+160, KscreenW-30, 150) collectionViewLayout:flowLayout];
    photosList.bounces = NO;
    photosList.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    photosList.scrollIndicatorInsets = photosList.contentInset;
    photosList.delegate = self;
    photosList.dataSource = self;
    photosList.backgroundColor = [UIColor clearColor];
    photosList.alwaysBounceVertical = YES;
    [self.scrV addSubview:photosList];

    [photosList registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"imagePickerCell"];

}

#pragma mark --- collectionV代理
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if(photos.count==0){
        return 1;
    }else{
        return photos.count+1;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"imagePickerCell" forIndexPath:indexPath];

    if(photos.count==indexPath.row){
        UIImageView *imgView = (UIImageView *)[cell.contentView viewWithTag:1];
        if (!imgView) {
            imgView = [[UIImageView alloc] initWithFrame:cell.bounds];
            imgView.contentMode = UIViewContentModeScaleAspectFill;
            imgView.clipsToBounds = YES;
            imgView.tag = 1;
            [cell addSubview:imgView];
        }
        [imgView setImage:[UIImage imageNamed:@"upload"]];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(upladImage:)];
        [cell addGestureRecognizer:tap];
    }else{
        ALAsset *asset = photos[indexPath.row];
        UIImageView *imgView = (UIImageView *)[cell.contentView viewWithTag:1];
        if (!imgView) {
            imgView = [[UIImageView alloc] initWithFrame:cell.bounds];
            imgView.contentMode = UIViewContentModeScaleAspectFill;
            imgView.clipsToBounds = YES;
            imgView.tag = 1;
            [cell addSubview:imgView];
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(preview:)];
            [cell addGestureRecognizer:tap];
        }
        cell.tag = indexPath.item;
        [[JFImageManager sharedManager] thumbWithAsset:asset resultHandler:^(UIImage *result) {
            if (cell.tag==indexPath.item)
            {
                imgView.image = result;
            }
        }];
    }
    return cell;
}

-(void)upladImage:(UITapGestureRecognizer *)tap{
    JFImagePickerController *picker = [[JFImagePickerController alloc] initWithRootViewController:nil];
    picker.pickerDelegate = self;
    [self presentViewController:picker animated:YES completion:nil];
}

- (void)preview:(UITapGestureRecognizer *)tap{
    UIView *temp = tap.view;
    JFImagePickerController *picker = [[JFImagePickerController alloc] initWithPreviewIndex:temp.tag];
    picker.pickerDelegate = self;
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma mark - ImagePicker Delegate
- (void)imagePickerDidFinished:(JFImagePickerController *)picker{
    [photos removeAllObjects];
    [photos addObjectsFromArray:picker.assets];

    [photosList reloadData];
    [self imagePickerDidCancel:picker];
}

- (void)imagePickerDidCancel:(JFImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}


-(void)CreateSrcV
{
    self.scrV = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, KscreenW, KscreenH)];
    [self.view addSubview:self.scrV];
    self.scrV.pagingEnabled = NO;
    self.scrV.showsVerticalScrollIndicator = NO;
    self.scrV.contentSize = CGSizeMake(kScreenWidth, kScreenHeight*2);
}

-(void)CreateTagV
{
    UILabel *ClassName = [[UILabel alloc]initWithFrame:CGRectMake(15, 20, KscreenW, 20)];
    ClassName.text = @"班级";
    [self.scrV addSubview:ClassName];
    ClassName.font = [UIFont systemFontOfSize:14];
    ClassName.textColor = UIColors(0x565657);

    self.TagV = [[JCTagListView alloc]initWithFrame:CGRectMake(15, 50, kScreenWidth-30, 60)];
     [self.scrV addSubview:self.TagV];
    self.TagV.tagTextColor = UIColors(0x656565);
    self.TagV.tagStrokeColor = PKCOLOR(239, 239, 239);
    self.TagV.tagBackgroundColor = PKCOLOR(251, 249, 249);
    self.TagV.tagSelectedBackgroundColor = PKCOLOR(251, 249, 249);
    self.TagV.tagSelectedTextColor = UIColors(MainColor);
    self.TagV.selecttagStrokeColor = UIColors(MainColor);

    self.TagV.tagTextFont = [UIFont systemFontOfSize:14];
    self.TagV.canSelectTags = YES;
    self.TagV.tagCornerRadius = 5;

    UILabel *LessonIntroduceL = [[UILabel alloc]initWithFrame:CGRectMake(15, 50+self.TagV.frame.size.height+10, KscreenW, 20)];
    LessonIntroduceL.tag = 101;
    [self.scrV addSubview:LessonIntroduceL];
    LessonIntroduceL.textColor = UIColors(0x565656);
    LessonIntroduceL.text = @"课例介绍";
    LessonIntroduceL.font = [UIFont systemFontOfSize:14];
    
}



-(void)CreateTextV
{
    self.textV = [[PlaceholderTextView alloc]initWithFrame:CGRectMake(15, 50+self.TagV.frame.size.height+10+20+10, KscreenW-30, 150)];
    [self.scrV addSubview:self.textV];
    self.textV.layer.masksToBounds = YES;
    self.textV.layer.cornerRadius = 5;
    self.textV.layer.borderColor = UIColors(0xEFEFEF).CGColor;
    self.textV.layer.borderWidth = 1;
    self.textV.placeholder = @"请输入课程例介绍";
}


-(void)CreateFabu
{
    self.FaBuBtn = [UIButton buttonWithType:(UIButtonTypeSystem)];
    [self.FaBuBtn setTitle:@"发布" forState:(UIControlStateNormal)];
    [self.FaBuBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    self.FaBuBtn.backgroundColor = UIColors(MainColor);
    self.FaBuBtn.layer.cornerRadius = 5;
    self.FaBuBtn.layer.masksToBounds = YES;
    [self.FaBuBtn addTarget:self action:@selector(Commit) forControlEvents:(UIControlEventTouchUpInside)];

    [self.scrV addSubview:self.FaBuBtn];
    [self.FaBuBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(10);
        make.right.equalTo(self.view.mas_right).offset(-10);
        make.top.equalTo(self.textV.mas_bottom).offset(150*KscreenH/667);
        make.height.mas_equalTo(45);
        make.bottom.equalTo(self.scrV.mas_bottom).offset(-10);
    }];

}

-(void)GetClassRequest
{
    
    [RequestManager RequstWithUrl:@"/index.php?g=App&m=TeacherCourse&a=courseList" parmDic:@{@"tid":[[NSUserDefaults standardUserDefaults]objectForKey:@"tid"]} requestType:RequestGET  Success:^(id data)
    {
        self.ClassArr = data;
        self.TagV.tags = self.ClassArr;
        [self.TagV.collectionView reloadData];

        self.TagV.frame = CGRectMake(0, 40, KscreenW, self.ClassArr.count/2.0*52);
        self.TagV.backgroundColor = [UIColor whiteColor];

        UIView *KeliV = [self.view viewWithTag:101];
        KeliV.frame = CGRectMake(15, self.TagV.frame.origin.y+self.TagV.frame.size.height+10, KscreenW, 20);
         self.textV.frame =CGRectMake(15, 50+self.TagV.frame.size.height+10+20+10, KscreenW-30, 150);
        photosList.frame =CGRectMake(15, 10+self.textV.frame.size.height+self.textV.frame.origin.y ,KscreenW-30, 150);
        

        [self.view setNeedsUpdateConstraints];
        [self.view updateConstraintsIfNeeded];
        [self.view layoutIfNeeded];

    } error:^(NSError *error) {

    }];
}


-(void)Commit
{
    [animationView showInView:self.view];

    dispatch_queue_t queueF = dispatch_queue_create("KeliUp", DISPATCH_QUEUE_CONCURRENT);
    dispatch_sync(queueF, ^{
        if (photos.count==0)
        {
            [animationView dismiss];
            [self postMessageimageArr:[@{} mutableCopy]];
        }else
        {
            NSMutableArray *indexArr = [@[]mutableCopy];
            for (NSInteger i = 0; i < photos.count; i++)
            {
                ALAsset *asset = photos[i];

                UIImage *upimage = [ASSETHELPER getImageFromAsset:asset type:ASSET_PHOTO_FULL_RESOLUTION];


                [[UploadImage sharedClient]doUploadImage:@"/index.php?g=App&m=Index&a=uploadsImgone" parameters:@{@"uid":[[NSUserDefaults standardUserDefaults]objectForKey:kUserId],@"access_token":[[NSUserDefaults standardUserDefaults]objectForKey:kAccessToken]} image:upimage successBlock:^(id responseBody)
                 {
                     NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseBody options:0 error:nil];
                     if ([dic[@"flag"]isEqualToString:@"Success"]) {
                         NSDictionary *imageAndIndexDic = @{@"index":[NSString stringWithFormat:@"%ld",i],@"imageUrl":dic[@"data"]};

                         [indexArr addObject:imageAndIndexDic];

                         if (indexArr.count == photos.count)
                         {
                             [animationView dismiss];
                             [self postMessageimageArr:indexArr];
                         }
                     }else
                     {
                         [animationView dismiss];
                         [HUD showText:dic[@"msg"] AfterTime:1];
                     }
                 } failureBlock:^(NSString *error)
                 {
                     [animationView dismiss];
                 }];
            }
        }
    });

}

-(void)postMessageimageArr:(NSMutableArray *)picArr;
{
    NSMutableArray *cid_arr = [@[] mutableCopy];
    for (NSDictionary *classDic in self.TagV.selectedTags)
    {
        [cid_arr addObject:classDic[@"cid"]];
    }
    if (cid_arr.count == 0)
    {
        [HUD showText:@"请选择班级" AfterTime:1];
        return;
    }

    NSMutableArray *upimageArr = [NSMutableArray array];

    for (NSInteger i = 0; i<picArr.count; i++)
    {
        for (NSDictionary *imageDic in picArr)
        {
            if ([imageDic[@"index"] isEqualToString:[NSString stringWithFormat:@"%ld",i]])
            {
                [upimageArr addObject:imageDic[@"imageUrl"]];
            }
        }
    }

    [RequestManager RequstWithUrl:@"/index.php?g=App&m=TeacherCourseep&a=addEp" parmDic:@{@"tid":[[NSUserDefaults standardUserDefaults]objectForKey:@"tid"],@"cid_arr":cid_arr,@"title":self.textV.text,@"thumbs":upimageArr} requestType:RequestPOST Success:^(id data)
     {
         [self.navigationController popViewControllerAnimated:YES];
         [self.Delegate AddDataReloadData];
     } error:^(NSError *error) {

     }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
